package com.sxt;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 *****************************************************************************
 * DESC ：聊天服务器端. 
 * Author : 利宝项目组 
 * CREATEDATE ：2012-2-12 
 * MODIFYLIST ：       	Name 			 Date 			Reason/Contents
 * 				------------------------------------------------------ 
 * 				 	Junwei Zhang     2012-2-12		Created.
 ****************************************************************************
 **/
/**
 * 聊天服务器端. <br/>
 * 下午9:22:46 2012-2-12
 * 
 * @Author <a href="mailto:mestudying@sina.com">Junwei Zhang</a><br/>
 **/
public class ChatServer {

	private ServerSocket ss = null;
	
	private Socket s = null;
	
	private List<ClientConnection> clients = new ArrayList<ClientConnection>();
	
	public static void main(String[] args) {
		new ChatServer().start();
	}
	
	public void start(){
		boolean started = false;
		try {
			ss = new ServerSocket(8888);
			started = true;
		} catch (BindException e) {
			System.out.println("端口使用中...请关掉相关程序并重新运行服务器!");
			System.exit(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
			while (started) {
				try {
					s = ss.accept();
					ClientConnection conn = new ClientConnection(s);
					new Thread(conn).start();
					clients.add(conn);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	}

	class ClientConnection implements Runnable {

		private Socket s = null;

		private DataInputStream dis = null;
		
		private DataOutputStream dos = null;

		private boolean bConnected = false;

		public ClientConnection(Socket s) {
			this.s = s;
			try {
				dis = new DataInputStream(s.getInputStream());
				dos = new DataOutputStream(s.getOutputStream());
				bConnected = true;
				System.out.println("---A client connected!---");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		public void send(String msg){
			try {
				dos.writeUTF(msg);
			} catch (IOException e) {
				clients.remove(this);
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			ClientConnection c = null;
			try {
				while (bConnected) {
					String str = dis.readUTF();
					System.out.println("----" + str + "----");
					for(int size = 0; size < clients.size(); size ++){
						c = clients.get(size);
						c.send(str);
					}
				}
			} catch (EOFException e) {
				System.out.println("-----The client is closed.-----");
			} catch(IOException e){
				e.printStackTrace();
			} finally {
				try {
					if (dis != null) dis.close();
					if (dos != null) dos.close();
					if (s != null) s.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// dis.close();
		}

	}

}
